import json
import os
import random
import re
import time

from flask import Blueprint, request, jsonify

from db import db1

bp_course = Blueprint("course", __name__)


@bp_course.route('/courseM', methods=['POST', 'GET', 'PUT', 'DELETE'])
def couponM():
    # 添加
    if request.method == "POST":
        # 获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造sql语句
        sql = "insert into coupon values(0,'%s',%d,'%s','%s')" % (
            data['name'], int(data['total']), data['stime'], data['etime'])
        # pymysql
        db1.insert(sql)
        # 返回结果
        return 'ok'
    elif request.method == 'GET':
        id = request.args.get('id')
        sql = "select * from coupon where id=%d" % (int(id))
        res = db1.find(sql)
        return jsonify({'code': 200, 'coupon': res})
    elif request.method == 'PUT':
        # 获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update coupon set name='%s',total=%d,startime='%s',endtime='%s' where id=%d" % (
            data['name'], int(data['total']), data['stime'], data['etime'], int(data['id']))
        db1.insert(sql)
        return jsonify({'code': 200})
    elif request.method == 'DELETE':
        id = request.args.get('id')
        sql = "delete from coupon where id=%d" % (int(id))
        db1.insert(sql)
        return jsonify({'code': 200})


from utils.myfile import myfile


# 文件上传
@bp_course.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    myfile.file_mkdir(2)
    file.save(os.path.join('./static/upload/2', file.filename))
    return 'ok'


@bp_course.route('/city', methods=['POST', 'GET'])
def city():
    if request.method == "POST":
        data = request.form
        sql = "insert into city values (0,'%s')" % (data['name'])
        db1.insert(sql)
        return jsonify({'code': 200})

    elif request.method == "GET":
        sql = "select * from city"
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})


@bp_course.route('/product', methods=['POST', 'GET'])
def product():
    if request.method == 'POST':
        city_id = request.data['cid']
        file = request.files['file']
        myfile.file_mkdir(city_id)
        file.save(os.path.join('./static/upload/' + city_id, file.filename))
        return 'ok'
    else:
        cityid = request.args.get('cityid')
        if cityid == 0:
            sql = "select * from product"
        else:
            sql = "select * from product where city_id=%d" % (int(cityid))

        res = db1.findall(sql)
        return jsonify({"code": 200, "list": res})

        # @bp_course.route('/page',methods=['GET'])
        # def page():
        sort = request.args.get('sort')
        if cityid == '0':
            sql = "select * from product order by price %s limit %d, %d" % (sort, start, page_size)
            sql1 = "select count(id) from product"
            res = db1.find(sql1)
            total = res['count(id)']
        else:
            sql2 = "select * from product where city_id=%d order by price %s limit %d,%d" % (int(cityid), sort, start)
            db1.findall(sql2)


@bp_course.route('/ace')
def Ace():
    monkey = request.args.get('monkey')
    if not monkey:
        return jsonify({'res': '不能为空'})
    else:
        try:
            monkey = float(monkey)
        except:
            return jsonify({'res': '格式有误'})
    if monkey > 0.01:
        return 666
    elif monkey < 200:
        return 777


@bp_course.route('/sendMony', methods=['POST'])
def sendMony():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "insert into test_record(name,url,method,params,result) values ('%s','%s','%s','%s','%s')" % \
          (data['name'], data['url'], data['method'], data['params'], data['result'])
    db1.insert(sql)
    return jsonify({"code": 200, "res": "测试成功"})


@bp_course.route('/sendSms', methods=['POST'])
def sendSms():
    # 获取手机号
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    try:
        mobile = data['mobile']
    except:
        return jsonify({"code": 10011, 'mes': '不能为空'})

    # 验证手机号是否合法
    res = re.match('^1[3-9]\d{9}$', mobile)
    if not res:
        return jsonify({"code": 10010, 'mes': '手机号不合法'})
    # 检查上次发送是否超过一分钟，1分钟内不能发
    sql = "select stime from trecord where mobile='%s' order by id desc limit 1" % (str(mobile))
    record = db1.find(sql)
    if record:
        # 判断时间是否在一分钟以内
        seconds = int(time.time()) - int(record['stime'])
        if seconds < 60:
            return jsonify({"code": 10012, "mes": '一分钟内不能重复发送'})
    # 生成验证码，发送
    code = random.randint(100000, 999999)
    # 当发送成功写入记录表
    sql2 = "insert into trecord(mobile,code,stime) values('%s',%d,%d)" % (str(mobile), code, int(time.time()))
    db1.insert(sql2)
    return jsonify({"code": 200, 'mes': '发送成功'})


@bp_course.route('/tlogin', methods=['POST'])
def tlogin():
    # 获取手机号验证码
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    # 通过手机号去记录中表查询，查最近的一条
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1" % (data['mobile'])
    res = db1.find(sql)
    # 验证码过期时间验证
    if int(time.time()) - int(res['stime']) > 60:
        return jsonify({"code": 10020, 'mes': '验证码已经过期，重新发送'})
    # 验证是否相同

    if res['code'] == int(data['code']):
        # 用户表中查询手机号是否存在
        sql1 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user = db1.find(sql1)
        # 存在返回登录成功userid
        if user:
            return jsonify({"code": 200, 'userid': user['id'], 'mes': '登录成功'})
        # 不存在添加新用户返回userid
        sql2 = "insert into tuser(mobile) values('%s')" % (data['mobile'])
        db1.insert(sql2)
        sql3 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({"code": 200, 'userid': user3['id']})
    else:
        return jsonify({"code": 10021, 'mes': '验证码输入错误'})


@bp_course.route('search/', methods=['GET'])
def search():
    ip = request.remote_addr
    title = request.args.get('title')
    matter = title.strip()
    if not matter:
        return jsonify({"code": 10030, 'msg': '搜索内容不能为空'})
    if 1 <= len(matter) <= 10:
        sql = "select * from goods where title like '%" + matter + "%'"
        res = db1.findall(sql)
        sql1 = "select id from grecord where ip='%s' and title='%s'" % (ip, title)
        res1 = db1.find(sql1)
        if not res1:
            sql2 = "insert into grecord(title,ip) values ('%s','%s')" % (matter, ip)
            db1.insert(sql2)
        return jsonify({"code": 200, "list": res})
    else:
        return jsonify({"code": 10031, "msg": '搜索长度不合法'})


@bp_course.route('shop/', methods=['GET'])
def shop():
    id = request.args.get('id')
    if not id:
        sql = "select * from shop"
        res = db1.findall(sql)
        return jsonify({"code": "200", "list": res})
    else:
        sql1 = "select * from shop where id=%d" % (int(id))
        list = db1.find(sql1)
        return jsonify({"code": "200", "list": list})


@bp_course.route('/evaluate', methods=['POST'])
def evaluate():
    # shopid = request.args.get('shopid')
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = "insert into evaluate(content,shopid) values ('%s',%d)" % (data['content'], int(data['shopid']))
    db1.insert(sql)
    return jsonify({"code": "200"})


@bp_course.route('/blogin', methods=['POST'])
def blogin():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    try:
        username = data['user']
        password = data['password']
    except:
        return jsonify({"code": 2003, "mes": "用户名和密码不能为空"})
    if not all(['username', 'password']):
        return jsonify({"code": 2003, "mes": "用户名和密码不能为空"})
    # if not data['user']:
    #     return jsonify({"code": 2003, "mes": "用户名不能为空"})
    # elif not data['password']:
    #     return jsonify({"code": 2004, "mes": "密码不能为空"})
    sql = "select * from author where username='%s'" % username
    res = db1.find(sql)
    if res:
        if res['password'] == password:
            return jsonify({'code': 200, 'list': res})
        else:
            return jsonify({"code": 2006, 'mes': '密码错误'})
    else:
        return jsonify({"code": 2005, "mes": "此用户不存在"})
    #
    # if res['username'] == data['user']:
    #     if res['password'] == data['password']:
    #         return jsonify({'code': 200, 'list': res})
    #     elif res['password'] != data['password']:
    #         return jsonify({"code": 2006, "mes": "密码错误"})
    # elif res['username'] != data['user']:
    #     return jsonify({"code": 2005, "mes": "此用户不存在"})


@bp_course.route('/book', methods=['POST'])
def book():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form

